﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NiuX.Auditing;
using NiuX.Data;
using NiuX.Domain.Entities;

namespace NiuX.Domain.Repositories
{
    public static class FakeDeleteExtensions
    {
        public static void FakeDelete<TEntity>(this IRepository<TEntity> repository, TEntity entity)
            where TEntity : EntityBase, new()
        {
            var propertyNames = new List<string>();

            if (entity is ISoftDelete)
            {
                propertyNames.Add(nameof(ISoftDelete.IsDeleted));
            }

            if (entity is IHasDeletionTime deletionTime)
            {
                deletionTime.DeletionTime = DateTime.Now;
                propertyNames.Add(nameof(IHasDeletionTime.DeletionTime));
            }

            if (entity is IHasModificationTime modificationTime)
            {
                modificationTime.LastModificationTime = DateTimeOffset.Now;
                propertyNames.Add(nameof(IHasModificationTime.LastModificationTime));
            }

            if (propertyNames.Count == 0)
            {
                return;
            }

            repository.UpdateAsync(entity).Wait();
        }

        public static async Task FakeDeleteAsync<TEntity>(this IRepository<TEntity> repository, TEntity entity)
            where TEntity : EntityBase, new()
        {
            var propertyNames = new List<string>();

            if (entity is ISoftDelete)
            {
                propertyNames.Add(nameof(ISoftDelete.IsDeleted));
            }

            if (entity is IHasDeletionTime deletionTime)
            {
                deletionTime.DeletionTime = DateTime.Now;
                propertyNames.Add(nameof(IHasDeletionTime.DeletionTime));
            }

            if (entity is IHasModificationTime modificationTime)
            {
                modificationTime.LastModificationTime = DateTimeOffset.Now;
                propertyNames.Add(nameof(IHasModificationTime.LastModificationTime));
            }

            if (propertyNames.Count == 0)
            {
                return;
            }

            await repository.UpdateAsync(entity);
        }
    }
}